/**
  * author hesai
  * 文书列表
  */
Ext.onReady(function() {
	     // shared reader
    var _reader = new Ext.data.JsonReader({totalProperty:'totalProperty',root:'root'}, [
     new Ext.grid.RowNumberer(),                     
      sm,
       {name: 'id',type:'long'},
       {name: 'pintsts', type: 'string'},
       {name: 'cphm', type: 'string'},

       {name: 'clbh', type: 'string'},
       {name: 'cx', type: 'string'},

       {name: 'fdjh', type: 'string'},
        {name: 'cjh', type: 'string'},
       {name: 'zyzyxqStr', type: 'string'},
        {name: 'writebz', type: 'string'}
    ]);

	
	//获取后台返回数据
	var _store = new Ext.data.Store({
             reader: _reader,
             proxy: new Ext.data.HttpProxy({url: path+'/bus-iccard-manage!toList.action',method:'POST'})
    });
    _store.on('beforeload', function(){
		_store.baseParams = {
			groupBy: _store.groupField ? _store.groupField : null,
			qyid: searchForm.form.findField('qyid').getValue(),//受理编号
			cphm: searchForm.form.findField('cphm').getValue()
		};
	}, this);
	 var searchForm = new Ext.FormPanel({
			region: 'north',
		title: '行政许可审批查询',
		labelAlign: 'right',
		renderTo:"inserDiv",
		
		height: 80,
		frame: true,
		plain: true,
		collapsible:true,
		collapsed:false,
		border: true,
		margins: '1 1 2 1',
		items: [{
			layout: 'column',
			items:[{
				columnWidth: .4,
				layout: 'form',
				items: [{
				xtype: 'basicCombo',
				fieldLabel: '运输公司',
				name: 'qyid',
				hiddenName: 'qyid',
				url: ctx + '/bus-iccard-manage!getCompany.action',
				allowBlank: true,
				anchor: '100%'
			}]
			},{
				columnWidth: .2,
				layout: 'form',
				items: [{
					xtype: 'textfield',
					fieldLabel: '车牌号码',
					emptyText:'车牌号码',
					name: 'cphm',
					editable:false,
					anchor: '100%'
				}]
			},{
				columnWidth: .3,
				layout: 'hbox',
				defaults:{margins:'0 5 0 40'},
				buttonAlign:"right",
				items:[{
					xtype: 'button',
					text: '&nbsp;查询',
					width: 50,
					iconCls: 'icon-find',
					handler: function(){
						_store.load();
						//searchForm.form.reset();
					},
					scope: this
				},{
					xtype: 'button',
					text: '清空',
					width: 50,
					handler: function(){
						searchForm.form.reset();
						_store.store.load();
					},
					scope: this
				}]
			}]
		}
		]
	});



	 Ext.QuickTips.init();

     var xg = Ext.grid;
     var win;
     var viewbutton = Ext.get('view-btn');
     var refreshbutton = Ext.get('refresh-btn');
     var bookPath;
     var bookpath2;
     var bookid;
     var bookkind;
     var dbid;
     var mid = Ext.get('id');
     //alert(mid.getValue());

     


    //表单底部 分页栏
    var _bbar = new Ext.PagingToolbar({
				pageSize : 20,
				store : _store,
				displayInfo : true,
				firstText : '第一页',
				lastText : '最后一页',
				nextText : '下一页',
				prevText : '上一页',
				refreshText : '刷新',
				beforePageText : '页',
				afterPageText : "至 {0}",
				displayMsg : '显示第 {0} 条到 {1} 条记录，一共 {2} 条',
				emptyMsg : '暂无数据'

	});
	//表单头部 工具栏
    _tbar = new Ext.Toolbar({ 
		items: 
		[ 
		           { text: '发卡', id: 'sendcard', iconCls: 'icon-edit' },
		           { text: '批量发卡', id: 'sendcards', iconCls: 'icon-edit'},
		           { text: '读卡', id: 'readcard', iconCls: 'icon-edit'},
		           { text: '打卡', id: 'printcard', iconCls: 'icon-edit'}
		]
	}); 

 
    
    ////////////////////////////////////////////////////////////////////////////////////////
    // 网格数据
    ////////////////////////////////////////////////////////////////////////////////////////
    var sm = new xg.CheckboxSelectionModel();
    //_grid.getStore().getCount() 获取当前页的数据数
    var _grid = new xg.GridPanel({
        store: _store,//数据源
        cm: new xg.ColumnModel([//列模型
            new Ext.grid.RowNumberer(),                     
            sm,
         {
			name:'id',
			header:'id',
			hidden: true
		},{
			name:'pintsts',
			header:'状态',
			width:90
		},{  
			name: 'cphm',  
			header: '车牌号',
			sortable: true,
			width: 120
			
		},{  
			name: 'clbh',  
			header: '标识编号',
			sortable: true,
			width: 120
			
		},{
			name: 'cx',  
			header: '车型',
			width: 100
			
		},{
			name: 'fdjh',  
			header: '发动机号',
			width: 180
		
		},{
			name: 'cjh',  
			header: '车架号',
			width: 180
		
		},{
			name: 'zyzyxqStr',  
			header: '有效日期',
			width: 180
		
		},{
			name: 'writebz',  
			header: '',
			width: 200
		
		}  ]),
        sm: sm,//复选框
        bbar:_bbar,// 表格底部分页工具栏
        tbar:_tbar,// 表格头部分页工具栏
        width:1366,
        height:450,
        frame : true,// 显示天蓝色圆角框
        title : "车辆列表",
        iconCls:'icon-grid',
        stripeRows : true,// 加上行条纹
        loadMask : true,// 加载数据时遮蔽表格
        columnLines : true,//显示列分割线
        renderTo: document.body
    });
      _grid.render('grid-book');

	var sendcards = Ext.get('sendcards'); 
	//批量发卡
	sendcards.on('click', function(e){
		var records = _grid.selModel.selections.keys;
		var cords=_grid.getSelectionModel().getSelections();
		 var recordsLen = records.length;
		 if(recordsLen > 0){
		    var ids="";
		    for(i=0;i<cords.length;i++){
		       ids+=cords[i].get("id")+",";
		    }
		    ids=ids.substring(0,ids.length-1);
		    var idarray = ids.split(",");
		    var index=0;
			send(index,idarray,cords);
	}
	});
	
	function send(index,idarray,sels){
		if(index==idarray.length){
			return;
		}
		var sel=sels[index];
		 $.ajax({
		  url: "bus-iccard-manage!writeCard.action",
		  type: "post",
		  data: { "id": idarray[index] }, //提交表单
		  datatype: "text",
		  timeout : 600000,
		  async: true,
		  /*complete: function(msg) { 
		    alert(msg);
		   },*/
		  success: function (data) {
		  	if(data=="true"){
			    sel.set('pintsts',"√");
             	  	sel.set('writebz',"<font color='read'>请放下一张卡</font>");
             	  	index++;
             	  	setTimeout(_writecard(index,idarray,sels),5000); 
             	  	
             	  	//send(index,idarray,sels);
			}else{
				//标识状态
				  sel.set('pintsts',"×<font color='read'>请重放卡</font>");
             	  	sel.set('writebz',"<font color='read'>请重放卡</font>");
             	  	sel.commit();
             	  	setTimeout(_writecard(index,idarray,sels),2000); 
			}
			
		  }
		  });
		} 

	
	function sleep(numberMillis) { 
	   var now = new Date(); 
	   var exitTime = now.getTime() + numberMillis;   
	   while (true) {      
           now = new Date(); 
           if (now.getTime() > exitTime) 
              return true; 
            else 
              return false;
          }
      }
      
	//发卡
	var sendcard = Ext.get('sendcard'); 
	sendcard.on('click', function(e){
		var val="";
		var sel = _grid.getSelectionModel().getSelections();
		var linenum=_grid.getSelectionModel().lastActive;
		if(linenum>0){
			var prevnum=linenum-1;
			_grid.store.getAt(prevnum).set("writebz" , "");
		    _grid.store.getAt(prevnum).commit();
		}
			if(sel.length == 1){
			  val = sel[0].get('id');
			}else{
				Ext.Msg.alert('系统提示', '只能选择一条记录，请重新选择！');
				return;
			}
		
		 	 Ext.Ajax.request({
				url: 'bus-iccard-manage!sendIccard.action',
				method: 'POST',
				timeout:900000,
				params: {
					id: val
				},
				success: function(response){
				Ext.getBody().unmask();
				var flag = response.responseText;
					if(flag=="true"){
					    sel[0].set('pintsts',"√");
	              	  	sel[0].set('writebz',"<font color='read'>请放下一张卡</font>");
					}else{
						//标识状态
						sel[0].set('pintsts',"×");
	              	  	sel[0].set('writebz',"<font color='read'>写卡失败</font>");
	              	  	sel[0].commit();
					}
				},
				failure: function(){
					Ext.Msg.alert('系统提示', '读取ic卡失败!');
				}
			});
	});

	//打卡
	var printcard = Ext.get('printcard'); 
	printcard.on('click', function(e){
		var sel = _grid.getSelectionModel().getSelections();
	 	 var busId="";
	 	 if(sel.length == 1){
			  busId = sel[0].get('id');
			}
		  var url="bus-iccard-manage!printViewCard.action?id="+busId;
	     YwUtil.openWin({url: url, w: 600, h: 300});
	});

	
	//读卡
	var readCard = Ext.get('readcard'); 
	readCard.on('click', function(e){
		  var action="bus-iccard-manage!readCard.action";
		  YwUtil.openWin({url: action, w: 700, h: 400});
	});
	
	//单独发卡方法
	function writecard(sel,sel2){
			var val="";
		 	 Ext.Ajax.request({
				url: 'bus-iccard-manage!writeCard.action',
				method: 'POST',
				async : false,
				timeout:900000,
				params: {
					id: sel.get('id')
				},
				success: function(response){
					Ext.getBody().unmask();
					var flag = response.responseText;
						if(flag=="true"){
						    sel.set('pintsts',"√");
		              	  	sel.set('writebz',"<font color='read'>请放下一张卡</font>");
		              	  	val="true";
						}else{
							//标识状态
							sel.set('pintsts',"×");
		              	  	sel.set('writebz',"<font color='read'>请重放卡</font>");
		              	  	sel.commit();
		              	  	val="false";
						}
				},
				failure: function(){
					Ext.Msg.alert('系统提示', '读取ic卡失败!');
					val="false";
				}
			});
			return val;
	}
	
	//发卡的回调方法
	function _writecard(obj,obj1,obj2) { 
		return function() { 
			send(obj,obj1,obj2); 
		} 
	} 

});